<template>
    <!-- :show-location="true" -->
    <view class="mains" :style="{ height: mapHeight + 'px' }">
        <map :style="{ height: mapHeight + 'px' }" @regionchange="regionchange($event, '1')" v-if="remark.length"
            class="map" id="around-company-map" ref="mapRef" :scale="scale" @callouttap="handleClick"
            :longitude="position?.position?.longitude" :latitude="position?.position?.latitude" :markers="remark">
            <!-- <cover-view :style="hStyle" class="cover-view" @click="handleControlTap" v-if="showCon">
                <cover-image class="h-image" src="/static/icon/c-ad.png"></cover-image>
            </cover-view> -->
            <cover-view slot="callout" v-if="remark.length">
                <cover-view :key="index" v-for="(item, index) in remark">
                    <cover-view class="customCallout" :marker-id="item.id"
                        style="width: fit-content; height: fit-content;">
                        <cover-view class="me">
                            <cover-view class="price">¥{{ item?.price?.toFixed(2) }}/度</cover-view>
                            <cover-view class="number">
                                <cover-view class="icon-box">
                                    <cover-image class="icon-image" :src="item.icon"></cover-image>
                                </cover-view>
                                <cover-view class="number-text">{{ item.usableNum }}/{{ item.countNum }}</cover-view>
                            </cover-view>
                        </cover-view>
                        <!-- 添加的小三角 -->
                        <cover-view class="triangle">
                            <cover-image class="triangle-img" src="/static/icon/dsj.png"></cover-image>
                        </cover-view>
                    </cover-view>
                </cover-view>
            </cover-view>
        </map>
        <view class="load" v-else>
            <wd-loading size="50px" color="#649270" />
        </view>
    </view>
</template>

<script setup>
import {
    nextTick,
    onMounted,
    ref,
    watch,
    getCurrentInstance
} from 'vue';
import { getAddress, getLocation, debounce } from '@/utils/tools'


const props = defineProps({
    position: {
        type: Object,
        default: () => { }
    },
    dListHeight: {
        type: Number,
        default: 0
    },
    dataList: {
        type: Array,
        default: () => []
    },
    kjShow: {
        type: Boolean,
        default: true
    },
    showCon: {
        type: Boolean,
        default: false
    }
})

const handleClick = (itemData) => {
    const markerId = itemData.markerId
    const index = remark.value.findIndex(item => item.id == markerId)
    let item = remark.value[index]
    uni.navigateTo({
        url: `/pages/index/indexListDetail?stationNo=${item.stationNo}&latitude=${item.latitude}&longitude=${item.longitude}&usableNum=${item.usableNum}&countNum=${item.countNum}`
    })
}

const emits = defineEmits(['changeMap'])
const regionchange = debounce(async (event, type) => {
    if (event.type == 'end') {
        let { latitude, longitude } = event.detail.centerLocation
        console.log(latitude, longitude, 'latitude, longitude')
        let address = await getAddress(latitude, longitude)
        let city = address?.data?.result?.address_component?.city || address?.data?.result?.address_component?.nation
        uni.setStorageSync('currentPosition', { latitude: latitude, longitude: longitude, city: address?.data?.result?.address_component?.province })
        emits('changeMap', { city, latitude, longitude })
    }
}, 500)
const systemInfo = uni.getSystemInfoSync();
let mapHeight = ref(0)
let hStyle = ref({})
watch(() => props.dListHeight, (newVal) => {
    if (newVal) {
        nextTick(() => {
            computedMapHeight(newVal)
            hStyle.value = {
                'position': 'absolute',
                'left': '95%',
                'top': '90%',
                'transform': 'translate(-50%, -50%)'
            }
        })
    }
}, { immediate: true })

// 获取地图高度
const computedMapHeight = (height) => {
    let remainingHeight = systemInfo.windowHeight;
    mapHeight.value = remainingHeight - height
}

onMounted(() => {
    computedMapHeight(props.dListHeight)
})

let latitude = ref('')
let longitude = ref('')

// 处理控件点击事件
const mapRef = ref()
const instance = getCurrentInstance();
async function handleControlTap() {
    console.log(scale.value, 'scale.value')
    uni.createMapContext('around-company-map', instance).getScale({
        success: res => {
            scale.value = res.scale
            nextTick(() => {
                scale.value = 13
            })
        }
    })
    // 如果需要更平滑的动画，可以使用 uni.createMapContext
    // const { latitude, longitude } = await getLocation();
    // const addressRes = await getAddress(latitude, longitude)
    let latitude = JSON.parse(uni.getStorageSync('position')).position.latitude
    let longitude = JSON.parse(uni.getStorageSync('position')).position.longitude
    let city = JSON.parse(uni.getStorageSync('position')).addressName
    remark.value[0].latitude = latitude
    remark.value[0].longitude = longitude
    uni.createMapContext('around-company-map', instance).moveToLocation({
        latitude: latitude,
        longitude: longitude
    })
    // emits('changeMap', {
    //     city: city,
    //     latitude: latitude,
    //     longitude: latitude
    // })

}

let scale = ref(13)
const remark = ref([])
const setPosition = async (position) => {
    // if (position?.position?.latitude && position.position.longitude) {
    // 确保使用 props.dataList 而不是 props?.dataList
    // 先处理数据列表
    remark.value = props.dataList.map(item => {
        return {
            id: item.id,
            latitude: item.latitude,
            longitude: item.longitude,
            iconPath: '/static/icon/tran.png',
            icon: '/static/icon/list-d.png',
            rotate: 0,
            width: 0,
            height: 0,
            // anchor: { x: 0.5, y: 1 },
            customCallout: {
                // anchorY: 70,
                // anchorX: 0,
                display: 'ALWAYS',
            },
            price: item.price,
            usableNum: item.usableNum,
            countNum: item.countNum,
            stationNo: item.stationNo,
        }
    });
    // 添加当前位置标记
    remark.value.unshift({
        id: 223321,
        latitude: uni.getStorageSync('currentPosition').latitude,
        longitude: uni.getStorageSync('currentPosition').longitude,
        iconPath: '/static/icon/c-address.png',
        width: 40,
        height: 40,
        anchor: { x: 0.5, y: 1 }
    })
    // remark.value = [{
    //     id: 223321,
    //     // latitude: position.position.latitude,
    //     // longitude: position.position.longitude,
    //     latitude: uni.getStorageSync('currentPosition').latitude,
    //     longitude: uni.getStorageSync('currentPosition').longitude,
    //     iconPath: '/static/icon/c-address.png',
    //     width: 40,
    //     height: 40,
    //     anchor: { x: 0.5, y: 1 }
    // }, ...markers]; // 使用展开运算符确保响应式更新
    // initMarkerCluster()
    console.log('更新后的标记:', remark.value);
    // }
}


watch(() => props.position, (newVal) => {
    nextTick(() => {
        // setPosition(newVal);
        // uni.setStorageSync('currentPosition', { latitude: props.position.position.latitude, longitude: props.position.position.longitude, city: props.position.addressName })
        setPosition()
    });
}, { deep: true, immediate: true });

// 添加对 dataList 的单独监听
watch(() => props.dataList, (newVal) => {
    if (newVal?.length && props.position) {
        nextTick(() => {
            setPosition(props.position);
        });
    }
}, { deep: true });


const initMarkerCluster = () => {
    nextTick(() => {
        uni.createMapContext('around-company-map', instance).initMarkerCluster({
            points: remark.value.map(item => ({
                latitude: item.latitude,
                longitude: item.longitude,
            }))
        })
    })
}

onMounted(async () => {

})
</script>

<style lang="scss" scoped>
.map {
    width: 100%;
}

.mains {
    position: relative;
}

.cover-view {
    position: absolute;
    left: 95%;
    top: 80%;
    transform: translate(-50%, -50%);
    z-index: 1;

    .h-image {
        width: 30px;
        height: 30px;
    }
}

.load {
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 60vh;
}

/* 气泡容器，用于定位 */
.customCallout {
    position: relative;
    width: 100%;
    display: flex;
    justify-content: center;
    margin-top: 50px;
    /* 根据需要调整 */
}

/* 气泡主体 */
.me {
    position: relative;
    background-color: #55946d;
    border-radius: 10px;
    padding: 10rpx 20rpx;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 20rpx;

    /* 控制气泡最大宽度 */
    .price {
        color: #fff;
        font-weight: 700;
    }

    .number {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 10rpx;

        .icon-box {
            width: 35rpx;
            height: 35rpx;
            background-color: #fff;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 4px;

            .icon-image {
                width: 25rpx;
                height: 25rpx;
            }
        }

        .number-text {
            color: #fff;
            font-weight: 700;
        }
    }
}



/* 在原有样式基础上添加 */
.customCallout {
    position: relative;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    // margin-top: 50px;

    .triangle {
        .triangle-img {
            width: 20px;
            height: 20px;
            margin-top: -20rpx;
        }

        /* 裁剪成三角形 */
        /* 三个顶点坐标 */
        /* 旋转45度变成三角形 */
    }
}

// /* 移除原来的 ::after 伪元素样式 */
// .me::after {
//     display: none;
// }

// .customCallout {
//     position: relative;
//     background-color: #55946d;
//     border-radius: 8px;
//     padding: 10px;
//     margin-top: 50px;
// }

// .triangle {
//     position: absolute;
//     bottom: -10px;
//     left: 50%;
//     transform: translateX(-50%);
//     width: 162px;
//     height: 102px;
// }</style>